const { src, dest, series } = require('gulp');
const clean = require('gulp-clean');
const replace = require('gulp-replace');
const terser = require('gulp-terser');
const cleanCSS = require('gulp-clean-css');

const basePath = '/lastepoch';
const assetHost = {
  local: 'http://127.0.0.1:8080',
  dev: 'https://test.d2core.com/lastepoch',
  prod: 'https://www.d2core.com/lastepoch',
};

function cleanTask() {
  return src('dist')
    .pipe(clean());
}

// 复制资源到dist目录
function copy() {
  return src(['src/**'])
    .pipe(dest('dist'));
}

// 替换css中图片路径
function replaceCSSUrl(env) {
  return src('dist/**/*.css')
  .pipe(replace('url(/', `url(${basePath}/`))
  .pipe(replace('url(\'/', `url(\'${basePath}/`))
  .pipe(dest('dist'));
}

// 替换js中加载json的路径
function replaceJSUrl(env) {
  return src(['dist/**/*.js'])
    .pipe(replace(assetHost.local, assetHost[env]))
    .pipe(dest('dist'))
}

// 主js最小化
function minifyLogicJS() {
  return src(['src/logic/*.js'])
    .pipe(terser())
    .pipe(dest('dist/logic'));
}

// 主css最小化
function minifyCSS() {
  return src('src/logic/*.css')
    .pipe(cleanCSS({ compatibility: 'ie8' }))
    .pipe(dest('dist/logic'));
}

exports.dev = series(cleanTask, copy, replaceCSSUrl, minifyLogicJS, () => replaceJSUrl('dev'), minifyCSS);
exports.default = series(cleanTask, copy, replaceCSSUrl, minifyLogicJS, () => replaceJSUrl('prod'), minifyCSS);
